package com.benny_driving_dri.util;

import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JsonUtil2 {
	private JsonUtil2() {
	}

	private static class JsonUtilHolder {
		private static JsonUtil2 instance = new JsonUtil2();
	}

	public static JsonUtil2 getInstance() {
		return JsonUtilHolder.instance;
	}

	public String object2json(List<?> objects) throws Exception {
		JSONArray mJsonA = new JSONArray();
		// mJsonA.add(DefaultResUtil.getDefaultJson());
		for (Object object : objects) {
			String[] attributes = ReflectUtil.getAttribute(object);
			String[] values = ReflectUtil.getFiledValues(object);
			JSONObject mJsonO = new JSONObject();
			for (int i = 0; i < attributes.length; i++) {
				mJsonO.put(attributes[i], values[i]);
			}
			mJsonA.put(mJsonO);
		}
		String res = mJsonA.toString();
		return res;
	}

	// public List<Object> json2object(String json, Object obj) throws Exception
	// {
	// System.out.println("json: " + json);
	// JSONArray mJsonA = new JSONArray(json);
	// System.out.println("json: -------------" + json);
	// String[] attributes = ReflectUtil.getAttribute(obj);
	// List<Object> mObjs = new LinkedList<Object>();
	// for (int i = 0; i < mJsonA.length(); i++) {
	// Object mObj = Class.forName(obj.getClass().getName()).newInstance();
	// JSONObject mJsonO = mJsonA.optJSONObject(i);
	// if (mJsonO.has(BaseImpl.JSON_STATE_NAME)) {
	// String errorFromServer = "";
	// if (BaseImpl.JSON_STATE_VALUE_SUCCESS
	// .equals((errorFromServer = (String) mJsonO
	// .get(BaseImpl.JSON_STATE_NAME))))
	// continue;
	// else {
	// Log.e("ServerError", errorFromServer);
	// break;
	// }
	// }
	// for (int j = 0; j < attributes.length; j++) {
	// String attribute = attributes[j];
	// String firstLetter = attribute.substring(0, 1).toUpperCase();
	// String setter = "set" + firstLetter + attribute.substring(1);
	// Method method = obj.getClass().getMethod(setter,
	// new Class[] { String.class });
	// String value = "";
	// try {
	// value = (String) mJsonO.get(attribute);
	// } catch (JSONException e) {
	// }
	// // method.invoke(mObj, new Object[] { mJsonO.get(attribute) });
	// method.invoke(mObj, new Object[] { value });
	// }
	// mObjs.add(mObj);
	//
	// }
	// return mObjs;
	// }
}
